package com.stox.util;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;

import com.stox.dto.web.BeanDescriptor;
import com.stox.dto.web.BeanPropertyDescriptor;

public class BeanUtil {

	public static BeanDescriptor introspectBean(Object bean, boolean includeBean){
		BeanDescriptor beanDescriptor = new BeanDescriptor();
		beanDescriptor.setBean(includeBean ? bean : null);
		beanDescriptor.setType(bean.getClass());
		beanDescriptor.setProperties(new ArrayList<>());
		for(Method method : bean.getClass().getMethods()){
			if(method.getName().startsWith("set") && 1 == method.getParameterCount()){
				BeanPropertyDescriptor beanPropertyDescriptor = new BeanPropertyDescriptor();
				beanDescriptor.getProperties().add(beanPropertyDescriptor);
				beanPropertyDescriptor.setBeanDescriptor(includeBean ? beanDescriptor : null);
				beanPropertyDescriptor.setName(method.getName().substring(3));
				beanPropertyDescriptor.setType(method.getParameterTypes()[0]);
				try {
					Object value = bean.getClass().getMethod("get"+beanPropertyDescriptor.getName(), new Class<?>[0]).invoke(bean, new Object[0]);
					beanPropertyDescriptor.setValue(value);
				} catch (IllegalAccessException | IllegalArgumentException
						| InvocationTargetException | NoSuchMethodException
						| SecurityException e) {
					try {
						Object value = bean.getClass().getMethod("is"+beanPropertyDescriptor.getName(), new Class<?>[0]).invoke(bean, new Object[0]);
						beanPropertyDescriptor.setValue(value);
					} catch (IllegalAccessException | IllegalArgumentException
							| InvocationTargetException | NoSuchMethodException
							| SecurityException e1) {
						throw new RuntimeException(e);
					}
					
				}
			}
		}
		return beanDescriptor;
	}
	
}